<template>
  <div class="departments-container">
    <div class="app-container">
      <el-card class="tree-card">
        <el-row>
          <el-col :span="20"><h3 class="title">{{ company.name }}</h3></el-col>
          <el-col :span="4">
            <el-row>
              <el-col :span="12">{{ company
                .manager }}</el-col>
              <el-col :span="12">
                <el-dropdown @command="handleCommand">
                  <span class="el-dropdown-link">
                    操作<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="addChild">添加子部门</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <!-- <div class="custom-tree-container">
          <el-tree
            :data="data"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
          >
            <span slot-scope="{ node }" class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span>
                <el-button type="text" style="color:#000;margin-right:5px">
                  管理员
                </el-button>
                <el-dropdown>
                  <span class="el-dropdown-link">
                    操作<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>添加子部门</el-dropdown-item>
                    <el-dropdown-item>编辑部门</el-dropdown-item>
                    <el-dropdown-item>删除部门</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </span>
            </span>
          </el-tree>
        </div> -->
        <!--
          data 树形组件用的数据
          default-expand-all 展开所有的节点
          node-key 表示数据中是使用的那个属性来唯一标识这个节点
          expand-on-click-node 是否在点击节点的时候展开或者收缩节点， 默认值为 true，如果为 false，则只有点箭头图标的时候才会展开或者收缩节点。
         -->
        <el-tree
          :data="departments"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
        >
          <!--
            下面是作用于插槽
            node 代表节点对象，里面含有该节点的所有信息，比如：文字，数据，是否有子节点，层级，父节点。。。
            data 就代表当前这个这个节点的数据
            -->
          <!-- <span slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button type="text" size="mini">
                {{ data }}
              </el-button>
              <el-button type="text" size="mini" @click="handleClick(node)"> 操作 </el-button>
            </span>
          </span> -->
          <el-row
            slot-scope="{ data }"
            type="flex"
            justify="space-between"
            align="middle"
            style="width: 100%; height: 40px"
          >
            <el-col :span="20">
              {{ data.name }}
            </el-col>
            <el-col :span="4">
              <el-row type="flex" justify="end">
                <el-col>
                  <span style="padding-right:5px;">{{ data.manager }}</span>
                </el-col>
                <el-col>
                  <el-dropdown @command="handleCommand">
                    <span> 操作 <i class="el-icon-arrow-down" /> </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item :command="deforehandleCommand('add',data)">添加子部门</el-dropdown-item>
                      <el-dropdown-item :command="deforehandleCommand('edit',data)">编辑部门</el-dropdown-item>
                      <el-dropdown-item :command="deforehandleCommand('delete',data)">删除部门</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-tree>
      </el-card>
    </div>

    <!--添加或者编辑 弹出框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      @close="closeDialog"
    >
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="1-50个字符" style="width: 80%;" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="ruleForm.code" placeholder="1-50个字符" style="width: 80%;" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="ruleForm.manager" placeholder="请选择负责人" style="width: 80%;">
            <el-option v-for="item in leader" :key="item.id" :label="item.username" :value="item.username" />

          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="ruleForm.introduce" type="textarea" placeholder="1-300个字符" style="width: 80%" />
        </el-form-item>
      </el-form>
      <el-row slot="footer" type="flex" justify="center">
        <!-- 列被分为24 -->
        <el-col :span="6">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </el-col>
      </el-row>

    </el-dialog>

    <!-- 删除弹出框 -->

  </div>
</template>

<script>
import { getDepartment, addDepartment, editDepartment, getDepartmentDetail, getLeader, delDepartment } from '@/api/departments'
import { tranListToTreeData } from '@/utils/index'
export default {

  data() {
    const checkDepartmentName = async(rule, value, callback) => {
      const { data: { depts }} = await getDepartment()
      // 找的是同一个父级部门下面有没有同名的
      // 第一步应该先找到所有的有相同父级（点击添加的那个父级）的子节点
      // 第二步判断这些子节点中的名字，是否有一些和我输入的名字相同，如果有，那就重复了，如果没有那就没有重复
      let isRepeat = false
      if (this.dialogTitle === '添加部门') {
        const children = depts.filter(item => item.pid === this.itemData.id)
        isRepeat = children.some(item => item.name === value)
      } else {
        const brother = depts.filter(item => item.pid === this.itemData.pid && item.name !== this.itemData.name)
        isRepeat = brother.some(item => item.name === value)
      }
      isRepeat ? callback(new Error(`部门‘${value}’已存在！`)) : callback()
    }
    const checkDepartmentCode = async(rule, value, callback) => {
      const { data: { depts }} = await getDepartment()
      // 找的是同一个父级部门下面有没有同名的
      // 第一步应该先找到所有的有相同父级（点击添加的那个父级）的子节点
      // 第二步判断这些子节点中的名字，是否有一些和我输入的名字相同，如果有，那就重复了，如果没有那就没有重复
      let isRepeat = false
      if (this.dialogTitle === '添加部门') {
        isRepeat = depts.some(item => item.code === value)
      } else {
        isRepeat = depts.filter(item => item.id !== this.itemData.id).some(item => item.code === value)
      }
      isRepeat ? callback(new Error(`code‘${value}’已存在！`)) : callback()
    }
    return {
      departments: [],
      company: {},
      dialogVisible: false, // 弹出框
      dialogTitle: '',
      itemData: {},
      leader: [],
      ruleForm: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      },
      rules: {
        name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' },
          { validator: checkDepartmentName, trigger: 'blur' }
        ],
        code: [{ required: true, min: 1, max: 50, message: '部门编码不能为空', trigger: 'blur' },
          { validator: checkDepartmentCode, trigger: 'blur' }],
        manager: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],
        introduce: [{ required: true, min: 1, max: 300, message: '部门介绍不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getData()
    this.getLeader()
  },
  methods: {
    // 获取部门详情
    async getDepartmentDetail() {
      const { data } = await getDepartmentDetail(this.itemData.id)
      this.ruleForm = {
        name: data.name,
        code: data.code,
        manager: data.manager,
        introduce: data.introduce
      }
    },
    // 获取部门负责人
    async getLeader() {
      const res = await getLeader()
      this.leader = res.data
    },
    // 获取组织架构数据
    async getData() {
      const { data } = await getDepartment()
      this.company = { name: data.companyName, id: data.companyId, manager: '负责人' }
      this.departments = tranListToTreeData(data.depts, '')
    },

    deforehandleCommand(command, data) {
      return {
        command,
        data
      }
    },
    // 处理点击事件
    async handleCommand(command) {
      if (command === 'addChild') {
        this.ruleForm.pid = ''
        this.dialogVisible = true
        this.dialogTitle = '新增部门'
      }
      if (command.command === 'add') {
        this.itemData = command.data
        this.ruleForm.pid = this.itemData.id
        this.dialogVisible = true
        this.dialogTitle = '新增部门'
        console.log(this.itemData.id)
      } else if (command.command === 'edit') {
        this.dialogVisible = true
        this.dialogTitle = '编辑部门'
        this.itemData = command.data
        await this.getDepartmentDetail()
      } else if (command.command === 'delete') {
        this.itemData = command.data
        this.popupDeleteBox()
      }
    },
    // 重置模态框
    resetForm() {
      for (const key in this.ruleForm) {
        this.ruleForm[key] = ''
      }
    },
    // 关闭弹窗时清空表单
    closeDialog() {
      this.resetForm()
      // 将表单验证重置
      this.$refs.ruleForm.clearValidate()
    },
    // 处理确定按钮
    async handleConfirm() {
      if (this.dialogTitle === '新增部门') {
        this.$refs.ruleForm.validate(async(valid) => {
          if (valid) {
            await this.addDepartment(this.ruleForm)
          }
        })
      } else if (this.dialogTitle === '编辑部门') {
        await this.editDepartment(this.itemData.id, this.ruleForm)
      }
    },
    // 编辑数据
    async editDepartment(id, data) {
      const res = await editDepartment(id, data)
      if (res.success) {
        this.$message.success('编辑成功')
        this.dialogVisible = false
        await this.getData()
      }
    },

    // 添加数据
    async addDepartment(data) {
      if (this.itemData.name === this.ruleForm.name || this.itemData.code === this.ruleForm.code) {
        this.$message.error('部门名称或者部门编码已存在')
        return
      } else {
        const res = await addDepartment(data)
        if (res.success) {
          this.$message.success('添加成功')
          this.dialogVisible = false
          await this.getData()
        }
      }
    },
    // 删除弹出框
    popupDeleteBox() {
      this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delDepartment(this.itemData.id)
        if (res.success) {
          this.getData()
          this.$message({
            type: 'success',
            message: res.message
          })
        } else {
          this.$message({
            type: 'error',
            message: '删除失败'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-card {
  padding: 30px  140px;
  font-size:14px;
 .title {
    font-size: 14px;
    font-weight: 400;
    margin-bottom: 20px;
  }
}
// ::v-deep .el-input__inner,
// ::v-deep .el-textarea__inner{
//   width: 80%;
// }
// ::v-deep .el-input--suffix{
//   width: 100%;
// }

</style>
